package org.tinaelle.utils;

import java.util.Date;

import javax.servlet.http.HttpSession;

import org.tinaelle.ServiceLocator;
import org.tinaelle.common.dto.AdSessionDTO;
import org.tinaelle.common.dto.AdUserDTO;

public class Session {

	public final static String	KEY	= "OJC_SESSION";

	private AdSessionDTO	   currentSession;
	private AdUserDTO	       user;
	private AdUserDTO	       anonymous;

	public static Session get() {
		final HttpSession http = ServletUtils.getRequest().getSession();
		Session s = ( Session ) http.getAttribute( KEY );
		if ( s == null ) {
			http.setAttribute( KEY, s = new Session() );
		}
		return s;
	}

	public Session() {

		resetUser();
	}

	public AdUserDTO getUser() {
		if ( user == null ) {
			user = getAnonymous();
		}
		return user;
	}

	public AdSessionDTO getSession() {
		if ( currentSession == null ) {
			currentSession = new AdSessionDTO();
			currentSession.setLogin( new Date() );
			currentSession.setAdUserId( getUser().getAdUserId() );

			currentSession = ServiceLocator.instance().getAdSystemService().save( currentSession );
		}
		return currentSession;
	}

	public AdUserDTO getAnonymous() {
		if ( anonymous == null ) {
			anonymous = ServiceLocator.instance().getAdSecurityService().getUserByEmail( "anonymous" );
		}
		return anonymous;
	}

	public void resetUser() {
		user = null;
	}

	public void resetSession() {
		currentSession = null;
	}

	public void setUser(final AdUserDTO user) {
		this.user = user;
	}

	public void setSession(final AdSessionDTO session) {
		this.currentSession = session;
	}

	public boolean isLogged() {
		if ( user == null ) {
			return false;
		}
		if ( user.getAdUserId() == getAnonymous().getAdUserId() ) {
			return false;
		}
		return true;
	}

}
